package cn.weekimwee.map3d;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.utils.SpatialRelationUtil;
import com.amap.api.maps.utils.overlay.SmoothMoveMarker;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;

import java.util.ArrayList;
import java.util.List;

import cn.weekimwee.map3d.overlay.DrivingRouteOverlay;

public class Main2Activity extends AppCompatActivity {
    MapView mapView;
    AMap aMap;
    RouteSearch routeSearch;
    LatLonPoint startPoint = new LatLonPoint(29.86088,121.593371);
    LatLonPoint endPoint =new LatLonPoint(29.857785,121.580055);

    LatLng startLatLng = new LatLng(29.86088,121.593371);
    LatLng latLng1 = new LatLng(29.859353,121.592383);
    LatLng latLng2 = new LatLng(29.857641,121.591782);
    LatLng latLng3 = new LatLng(29.856692,121.591439);
    LatLng latLng4 = new LatLng(29.855454,121.591095);
    LatLng latLng5 = new LatLng(29.853007,121.590022);
    LatLng latLng6 = new LatLng(29.851183,121.588746);
    LatLng latLng7 = new LatLng(29.851593,121.586117);
    LatLng latLng8 = new LatLng(29.852151,121.582845);
    LatLng latLng9 = new LatLng(29.852244,121.579347);
    LatLng latLng10 = new LatLng(29.854422,121.577598);
    LatLng endLatLng = new LatLng(29.857785,121.580055);

    List<LatLng> all;/*所有经纬度*/
    List<LatLng> now;/*最近更新的一段路的两个经纬度*/

//    StartRunThread startRunThread;
    SmoothMoveMarker smoothMarker;
    DrivingRouteOverlay drivingRouteOverlay;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        mapView = findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        registerListener();
        routeSearch = new RouteSearch(this);
        routeSearch.setRouteSearchListener(new RouteSearch.OnRouteSearchListener() {
            @Override
            public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

            }

            @Override
            public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int i) {
                //这个里要写逻辑
                if(i == AMapException.CODE_AMAP_SUCCESS){
                    if(driveRouteResult!=null && driveRouteResult.getPaths()!=null){

                        final DrivePath drivePath = driveRouteResult.getPaths()
                                .get(0);
                        drivingRouteOverlay = new DrivingRouteOverlay(
                                Main2Activity.this, aMap, drivePath,
                                driveRouteResult.getStartPos(),
                                driveRouteResult.getTargetPos(), null);
                        drivingRouteOverlay.setNodeIconVisibility(false);//设置节点marker是否显示
                        drivingRouteOverlay.setIsColorfulline(false);//是否用颜色展示交通拥堵情况，默认true
                        drivingRouteOverlay.removeFromMap();
                        drivingRouteOverlay.addToMap();
                        drivingRouteOverlay.zoomToSpan();
                    }else{
                        Toast.makeText(Main2Activity.this, "没搜索到数据。。。", Toast.LENGTH_SHORT).show();
                    }
                }else{
                    Toast.makeText(Main2Activity.this,"没搜索到数据...+i->"+i,Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

            }

            @Override
            public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

            }
        });
        RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(startPoint, endPoint);
        RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo, RouteSearch.DrivingDefault, null,
                null, "");// 第一个参数表示路径规划的起点和终点，第二个参数表示驾车模式，第三个参数表示途经点，第四个参数表示避让区域，第五个参数表示避让道路
        routeSearch.calculateDriveRouteAsyn(query);// 异步路径规划驾车模式查询

        /*//平滑移动
        //1.造数据
        all = new ArrayList<>();
        all.add(startLatLng);
        all.add(latLng1);
        all.add(latLng2);
        all.add(latLng3);
        all.add(latLng4);
        all.add(latLng5);
        all.add(latLng6);
        all.add(latLng7);
        all.add(latLng8);
        all.add(latLng9);
        all.add(latLng10);
        all.add(endLatLng);

        startRunThread = new StartRunThread();
        startRunThread.start();*/
    }

    private void registerListener() {
        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {

            }
        });
        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                return false;
            }
        });
        aMap.setOnInfoWindowClickListener(new AMap.OnInfoWindowClickListener() {
            @Override
            public void onInfoWindowClick(Marker marker) {

            }
        });
        aMap.setInfoWindowAdapter(new AMap.InfoWindowAdapter() {
            @Override
            public View getInfoWindow(Marker marker) {
                return null;
            }

            @Override
            public View getInfoContents(Marker marker) {
                return null;
            }
        });
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    /*class StartRunThread extends Thread{
        boolean isRun = true;
        @Override
        public void run() {
            super.run();
            try {
                while(isRun){
                    handler.sendEmptyMessage(0);
                    Thread.sleep(3000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        public void close(){
            isRun = false;
        }
    }*/

   /* @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Log.e("eeeee","message---->");
            if(now==null||now.size()==0){
                now = new ArrayList<>();
                now.add(all.remove(0));
            }else if(now.size()==1){
                if(all.size()!=0)
                now.add(all.remove(0));
                else startRunThread.close();
            }else if(now.size()==2){
                //开始跑
                drivingRouteOverlay.removeStartMarker();
                if(smoothMarker!=null)smoothMarker.destroy();
                startMove();
                now.remove(0);
            }else if(now.size()!=0 &&all.size()==0){
                startRunThread.close();
            }
        }
    };*/

    private void startMove() {
        // 构建 轨迹的显示区域
        LatLngBounds bounds = new LatLngBounds(now.get(0), now.get(1));
        aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 50));

        // 实例 SmoothMoveMarker 对象
        smoothMarker = new SmoothMoveMarker(aMap);
        // 设置 平滑移动的 图标
        smoothMarker.setDescriptor(BitmapDescriptorFactory.fromResource(R.drawable.icon_car));

        // 取轨迹点的第一个点 作为 平滑移动的启动
        LatLng drivePoint = now.get(0);
        Pair<Integer, LatLng> pair = SpatialRelationUtil.calShortestDistancePoint(now, drivePoint);
        now.set(pair.first, drivePoint);
        List<LatLng> subList = now.subList(pair.first, now.size());

        // 设置轨迹点
        smoothMarker.setPoints(subList);
        // 设置平滑移动的总时间  单位  秒
        smoothMarker.setTotalDuration(4);

        // 设置  自定义的InfoWindow 适配器
        aMap.setInfoWindowAdapter(new AMap.InfoWindowAdapter() {
            @Override
            public View getInfoWindow(Marker marker) {
                return null;
            }

            @Override
            public View getInfoContents(Marker marker) {
                return null;
            }
        });
        // 显示 infowindow
        smoothMarker.getMarker().showInfoWindow();
        smoothMarker.startSmoothMove();
    }
}
